import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 路由懒加载
const Login = () => import('@/views/Login.vue')
const MainLayout = () => import('@/layouts/MainLayout.vue')
const Dashboard = () => import('@/views/Dashboard.vue')

// 设备管理
const EquipmentList = () => import('@/views/equipment/EquipmentList.vue')
const EquipmentDetail = () => import('@/views/equipment/EquipmentDetail.vue')
const EquipmentForm = () => import('@/views/equipment/EquipmentForm.vue')

// 设备申请
const EquipmentApplicationList = () => import('@/views/equipment/EquipmentApplicationList.vue')
const EquipmentApplicationForm = () => import('@/views/equipment/EquipmentApplicationForm.vue')

// 借还管理
const EquipmentBorrowList = () => import('@/views/borrow/EquipmentBorrowList.vue')
const EquipmentBorrowForm = () => import('@/views/borrow/EquipmentBorrowForm.vue')

// 设备统计
const EquipmentStatistics = () => import('@/views/statistics/EquipmentStatistics.vue')
const ConsumableStatistics = () => import('@/views/statistics/ConsumableStatistics.vue')
const EquipmentRepairList = () => import('@/views/statistics/EquipmentRepairList.vue')
const EquipmentScrapList = () => import('@/views/statistics/EquipmentScrapList.vue')

// 低值易耗品
const ConsumablePlanList = () => import('@/views/consumable/ConsumablePlanList.vue')
const ConsumablePlanForm = () => import('@/views/consumable/ConsumablePlanForm.vue')
const ConsumableReceiveList = () => import('@/views/consumable/ConsumableReceiveList.vue')
const ConsumableReceiveForm = () => import('@/views/consumable/ConsumableReceiveForm.vue')
const ConsumableQuery = () => import('@/views/consumable/ConsumableQuery.vue')

// 报表中心
const ReportCenter = () => import('@/views/report/ReportCenter.vue')

// 用户管理
const UserList = () => import('@/views/user/UserList.vue')
const UserForm = () => import('@/views/user/UserForm.vue')
const LaboratoryList = () => import('@/views/user/LaboratoryList.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表盘', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      // 设备管理
      {
        path: '/equipment',
        name: 'EquipmentList',
        component: EquipmentList,
        meta: { title: '设备管理', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment/detail/:id',
        name: 'EquipmentDetail',
        component: EquipmentDetail,
        meta: { title: '设备详情', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment/form/:id?',
        name: 'EquipmentForm',
        component: EquipmentForm,
        meta: { title: '设备登记', roles: ['ADMIN', 'LEADER'] }
      },
      // 设备申请
      {
        path: '/equipment-application',
        name: 'EquipmentApplicationList',
        component: EquipmentApplicationList,
        meta: { title: '设备申请', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment-application/form/:id?',
        name: 'EquipmentApplicationForm',
        component: EquipmentApplicationForm,
        meta: { title: '设备申请', roles: ['ADMIN', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment-application/:id',
        name: 'EquipmentApplicationDetail',
        component: () => import('@/views/equipment/EquipmentApplicationDetail.vue'),
        meta: { title: '申请详情', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      // 借还管理
      {
        path: '/equipment-borrow',
        name: 'EquipmentBorrowList',
        component: EquipmentBorrowList,
        meta: { title: '借还管理', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment-borrow/form/:id?',
        name: 'EquipmentBorrowForm',
        component: EquipmentBorrowForm,
        meta: { title: '设备借用', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment-borrow/detail/:id',
        name: 'EquipmentBorrowDetail',
        component: () => import('@/views/borrow/EquipmentBorrowDetail.vue'),
        meta: { title: '借还详情', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      // 设备统计
      {
        path: '/equipment-statistics',
        name: 'EquipmentStatistics',
        component: EquipmentStatistics,
        meta: { title: '设备统计', roles: ['ADMIN', 'LEADER'] }
      },
      {
        path: '/consumable-statistics',
        name: 'ConsumableStatistics',
        component: ConsumableStatistics,
        meta: { title: '易耗品统计', roles: ['ADMIN', 'LEADER'] }
      },
      {
        path: '/equipment-repair',
        name: 'EquipmentRepairList',
        component: EquipmentRepairList,
        meta: { title: '维修记录', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment-repair/form/:id?',
        name: 'EquipmentRepairForm',
        component: () => import('@/views/statistics/EquipmentRepairForm.vue'),
        meta: { title: '维修记录', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/equipment-scrap',
        name: 'EquipmentScrapList',
        component: EquipmentScrapList,
        meta: { title: '报废记录', roles: ['ADMIN', 'LEADER'] }
      },
      {
        path: '/equipment-scrap/form/:id?',
        name: 'EquipmentScrapForm',
        component: () => import('@/views/statistics/EquipmentScrapForm.vue'),
        meta: { title: '设备报废', roles: ['ADMIN', 'LEADER'] }
      },
      // 低值易耗品
      {
        path: '/consumable-plan',
        name: 'ConsumablePlanList',
        component: ConsumablePlanList,
        meta: { title: '易耗品计划', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/consumable-plan/form/:id?',
        name: 'ConsumablePlanForm',
        component: ConsumablePlanForm,
        meta: { title: '创建计划', roles: ['ADMIN', 'LAB_MANAGER'] }
      },
      {
        path: '/consumable-receive',
        name: 'ConsumableReceiveList',
        component: ConsumableReceiveList,
        meta: { title: '领用记录', roles: ['ADMIN', 'LEADER', 'LAB_MANAGER'] }
      },
      {
        path: '/consumable-receive/form/:id?',
        name: 'ConsumableReceiveForm',
        component: ConsumableReceiveForm,
        meta: { title: '物品领用', roles: ['ADMIN', 'LAB_MANAGER'] }
      },
      {
        path: '/consumable-query',
        name: 'ConsumableQuery',
        component: ConsumableQuery,
        meta: { title: '消耗查询', roles: ['ADMIN', 'LEADER'] }
      },
      // 报表中心
      {
        path: '/report',
        name: 'ReportCenter',
        component: ReportCenter,
        meta: { title: '报表中心', roles: ['ADMIN', 'LEADER'] }
      },
      // 用户管理
      {
        path: '/user',
        name: 'UserList',
        component: UserList,
        meta: { title: '用户管理', roles: ['ADMIN'] }
      },
      {
        path: '/user/form/:id?',
        name: 'UserForm',
        component: UserForm,
        meta: { title: '用户管理', roles: ['ADMIN'] }
      },
      {
        path: '/laboratory',
        name: 'LaboratoryList',
        component: LaboratoryList,
        meta: { title: '实验室管理', roles: ['ADMIN'] }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 简单的消息提示函数
const showMessage = (message, type = 'info') => {
  // 简单的消息提示实现
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'warning' ? 'bg-yellow-500' : 
    type === 'error' ? 'bg-red-500' : 
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)
  
  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    next('/')
    return
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!userStore.isLoggedIn) {
      showMessage('请先登录', 'warning')
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && to.meta.roles.length > 0) {
      if (!userStore.hasAnyRole(to.meta.roles)) {
        showMessage('权限不足', 'error')
        // 重定向到用户有权限的页面，而不是首页
        if (userStore.hasRole('ADMIN')) {
          next('/user')
        } else if (userStore.hasRole('LEADER')) {
          next('/equipment-statistics')
        } else if (userStore.hasRole('LAB_MANAGER')) {
          next('/equipment')
        } else {
          next('/')
        }
        return
      }
    }
  }
  
  next()
})

export default router
